// pages/index/index.js
import * as request from "../../../utils/request/file/file.js"
Page({

  /**
   * 页面的初始数据
   */

  data: {
    loadingMore: false,
    loading: false,
    value: '',
    file: [],
    current: 1,
    pageSize: 7,
    loadText: "加载中...",
    tatol: 0,
    hasMore: true,
  },
  onReachBottom: function () {


    if (!this.data.hasMore) {
      this.setData({
        loadingMore: true,
        loadText: "没有更多了"
      });
      setTimeout(() => {
        this.setData({
          loadingMore: false,
        });
      }, 800)
      return;
    }

    this.setData({
      loadingMore: true,
      loadText: "加载更多..."
    });
    let current = this.data.current + 1
    this.setData({
      current: current
    })
    this.getfileInfo()
  },
  preventDefault: function (e) {
    // 阻止触摸事件的默认行为，防止滚动  
    console.log(e)
    e.stopPropagation();
    e.preventDefault();
  },
  async openDOCX(event) {
    // wx.navigateTo({
    //   url: `/pages/index/article?id=${param}`,
    // })

    let session = wx.getStorageSync('session')
    const param = event.currentTarget.dataset.param
    console.log(param)
    this.setData({
      loading: true
    })
    let self = this
    try {
      let res = await request.queryFile({
        id: param
      }, session)
      console.log(res)
      let info = res.data.records[0]
      let filePath = info.fileIlk == "" ? wx.env.USER_DATA_PATH + `/${info.name}.docx` : wx.env.USER_DATA_PATH + `/${info.name}.${info.fileIlk}`
      console.log(filePath)
      const fs = wx.getFileSystemManager()

      fs.writeFile({
        filePath: filePath,
        data: wx.base64ToArrayBuffer(res.data.records[0].content), // 确保这是正确的二进制数据或编码后的字符串  
        encoding: "binary",
        success: function (writeRes) {
          console.log("成功写入文件", writeRes);
          wx.openDocument({
            filePath: filePath,
            fileType: res.data.records[0].fileIlk, // 根据文件类型设置
            success: function (res) {
              self.setData({
                loading: false
              })
              //console.log('文档打开成功',res);
            },
            fail: function (err) {
              console.error('文档打开失败', err);
              wx.showToast({
                title: '文档打开失败',
              })
            }
          });
        },
        fail: function (err) {
          //console.error("写入文件失败", err);  
        }
      })
    } catch (err) {
      self.setData({
        loading: false
      })
      wx.showToast({
        title: '文档打开失败',
        icon: "none"
      })
    }


  },
  enterSearch(e) {
    wx.navigateTo({
      url: '/pages/search/index',
    })
  },
  async onLoad(options) {
    let session = wx.getStorageSync('session')
    let res = await request.queryFile({
      id: 1
    }, session)
    this.setData({
      tatol: res.data.size
    })
    this.getfileInfo()
  },
  async getfileInfo() {
    this.setData({
      loadingMore: true,
      loadText: "加载更多..."
    });
    let session = wx.getStorageSync('session')
    //let strat = (this.data.current - 1) * this.data.pageSize
    let pageSize = this.data.pageSize
    let res = await request.listFilePro({
      current: this.data.current,
      pageSize: pageSize
    }, session)
    console.log(res.data.records)
    let arr = []
    arr = JSON.parse(JSON.stringify(this.data.file))
    if (res.code == 0) {
      for (const item of res.data.records) {
        arr.push(item)
      }
      this.setData({
        file: arr
      })
      console.log(arr)
      this.setData({
        loadingMore: false,
        hasMore: res.data.total > this.data.file.length,
      });
    } else {
      this.setData({
        loadText: "加载失败"
      });
      setTimeout(() => {
        this.setData({
          loadingMore: false
        });
      }, 300)
    }
    //console.log(this.data.file)

  },
  async handleDelete(event) {
    const param = event.currentTarget.dataset.param
    console.log(param)
    let session = wx.getStorageSync('session')
    let res = await request.deleteFile({
      id: param
    }, session)
    console.log(res)
    if (res.code == 0) {
      wx.showToast({
        title: '删除成功',
      })
      this.setData({
        file:[],
        current:1
      })
      this.getfileInfo()
    } else {
      wx.showToast({
        title: '删除失败',
        icon: "none"
      })
    }

  }
})